import json

import requests

from common.logger import logFile
from common.utils import enconde_bs64,decode64_str

logger = logFile('tester', 'all')

script_env = "https://www.retone-hearing.fit"

def warpper(func):
    def response_(*args, **kwargs):
        f = func(*args,**kwargs)
        print(args)
        res = requests.post(login_url, data=enconde_bs64(info))
        if res.status_code > 400 or (res.json()['data'] == None and res.json()['description'] != None):
            logger.error(
                "=============  登录   接口调用失败==========" + '\n' + str(
                    res.json()) + f'res.status_code = {res.status_code}')
            return False
        return str(res.cookies.values()[0])
        return f
    return response_


@warpper
def login(username, password='cc1234'):
    """
    登录接口
    :param username: 用户名
    :param password: 密码
    :return: 返回用户cookie
    """
    user = username
    passwd = password
    # 登录
    login_url = script_env + '/microServiceUser/responseEncode/requestDecode/login'
    info = {
        "type": 0,
        "sourcePlatform": "RETONE_FIT",
        "password": passwd,
        "loginObject": user
    }
    header = {"Content-Type": "application/json"}


def mqtt_conf(cookie):
    """
    去登录接口获取cookie信息,调用该接口
    :param username: 用户名
    :param passwd: 密码
    :return: 返回mqtt配置信息
    """
    mqtt_url = script_env + '/platformRetoneFit/api/mqtt/needAppUserAuth/responseEncode/requestDecode/getMqttConnectProperties'
    info = {}
    # cookie = login(username, passwd)
    res = requests.post(mqtt_url, info, cookie)
    if res.status_code != 200 or res.json()['data'] is None:
        logger.error('===== 获取mqtt配置信息接口失败 =========')
        logger.error(res.json())
    data_str = decode64_str(res.json()['data'])
    data = json.loads(data_str)
    dic_conf = {
        "appGuestPassword": "123456@appGuest.retone",
        "port": data['port'],
        "appGuestSendTopic": data['appGuestSendTopic'],
        "appGuestReceiveTopic": data['appGuestReceiveTopic'],
        "appGuestReceiveClientId": data['appGuestReceiveClientId'],
        "url": data['url'],
        "appGuestName": "appGuest"
    }
    # logger.error(dic_conf)
    return dic_conf


if __name__ == '__main__':
    login('cc1234')